package com.kgdev.cweb.mbean.global.application;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.ejb.EJB;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import com.kgdev.cweb.beans.i8n.impl.I8nShortBean;
import com.kgdev.cweb.beans.i8n.impl.I8nTextBean;
import com.kgdev.cweb.entities.i8n.I8nShort;
import com.kgdev.cweb.entities.i8n.I8nText;
import com.kgdev.cweb.resmng.i18n.MYSQLShortTextResourceBundle;
import com.kgdev.cweb.resmng.i18n.MYSQLTextResourceBundle;

@ManagedBean
@ApplicationScoped
public class ResourceBundleControl extends ResourceBundle.Control {

	@EJB
	I8nShortBean i8nShortBean;

	@EJB
	I8nTextBean i8nTextBean;
	
	public static final String FORMAT_MYSQL = "mysql";
	public static final String SHORT_TEXT_BUNDLE = "MYSQLShortTextResourceBundle";
	public static final String TEXT_BUNDLE = "DBTextResourceBundle";
	
	public ResourceBundleControl() {
	}

	@Override
	public List<String> getFormats(String baseName) {
		if (baseName == null)
			throw new NullPointerException();
		return Arrays.asList(FORMAT_MYSQL);
	}

	@Override
	public ResourceBundle newBundle(String baseName, Locale locale,
			String format, ClassLoader loader, boolean reload)
			throws IllegalAccessException, InstantiationException, IOException {
		ResourceBundle bundle = null;
		if (format.equals(FORMAT_MYSQL)) {
			if (baseName == SHORT_TEXT_BUNDLE) {
				HashMap<String, String> input = loadShortTextToMap(locale);
				bundle = new MYSQLShortTextResourceBundle(input);
			}
			if (baseName == TEXT_BUNDLE) {
				HashMap<String, String> input = loadTextToMap(locale);
				bundle = new MYSQLTextResourceBundle(input);
			}
		}
		return bundle;
	}

	private HashMap<String, String> loadShortTextToMap(Locale locale) {
		HashMap<String, String> resultHashMap = new HashMap<String, String>();

		List<I8nShort> i8nVc45s = i8nShortBean.findByLanguage(locale.getLanguage());

		for (I8nShort i8nVc45 : i8nVc45s) {
			resultHashMap.put(i8nVc45.getId().getVc45Key(), i8nVc45.getVc45Value());
		}

		return resultHashMap;
	}

	private HashMap<String, String> loadTextToMap(Locale locale) {
		HashMap<String, String> resultHashMap = new HashMap<String, String>();

		List<I8nText> i8nTexts = i8nTextBean.findByLanguage(locale.getLanguage());

		for (I8nText i8nText : i8nTexts) {
			resultHashMap.put(i8nText.getId().getTextKey(), i8nText.getTextValue());
		}

		return resultHashMap;
	}
}